<!-- 用户管理 -->
<template>
  <div class="app-container">
    <el-row>
      <!-- 用户列表 -->
      <el-col>
        <div class="search-bar">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                placeholder="用户名/昵称/手机号"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="毕业院校" prop="schoolId">
              <el-select
                v-model="queryParams.schoolId"
                filterable
                remote
                clearable
                placeholder="请输入院校名称搜索"
                :remote-method="getSchoolList"
                :loading="schoolLoading"
                style="width: 200px"
              >
                <el-option
                  v-for="item in schoolOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="学历" prop="academicDegreeCodes">
              <Dict
                v-model="queryParams.academicDegreeCodes"
                type="select-multiple"
                style="width: 200px"
                code="academic_degree"
              />
            </el-form-item>

            <el-form-item label="擅长领域" prop="expertiseList">
              <Dict
                v-model="queryParams.expertiseList"
                type="select-multiple"
                style="width: 200px"
                code="expertise_field"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="全部"
                clearable
                class="!w-[100px]"
              >
                <el-option label="正常" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>

            <el-form-item label="创建时间">
              <el-date-picker
                v-model="queryParams.createTime"
                :editable="false"
                class="!w-[240px]"
                type="daterange"
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="截止时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
          <div class="flex-x-between mb-10px">
            <div>
              <el-button type="success" icon="plus" @click="handleOpenDialog()">新增</el-button>
              <el-button
                type="danger"
                icon="delete"
                :disabled="selectIds.length === 0"
                @click="handleDelete()"
              >
                删除
              </el-button>
            </div>
            <div>
              <el-button icon="upload" @click="handleOpenImportDialog">导入</el-button>

              <el-button icon="download" @click="handleExport">导出</el-button>
            </div>
          </div>

          <el-table
            v-loading="loading"
            :data="pageData"
            border
            @selection-change="handleSelectionChange"
            @row-click="handleRowClick"
          >
            <el-table-column type="selection" width="45" align="center" />
            <el-table-column label="用户名" prop="username" width="120" />
            <el-table-column label="昵称" width="120" align="center" prop="nickname" />
            <el-table-column label="性别" width="60" align="center">
              <template #default="scope">
                <!-- 性别字典翻译 -->
                <DictLabel v-model="scope.row.gender" code="gender" />
              </template>
            </el-table-column>
            <el-table-column label="学历" width="80" prop="academicDegreeName" align="center" />
            <el-table-column label="毕业院校" width="180" align="center">
              <template #default="scope">
                {{ scope.row.schoolName || "--" }}
              </template>
            </el-table-column>
            <el-table-column label="擅长领域" align="center">
              <template #default="{ row }">
                <el-popover
                  placement="top"
                  :width="300"
                  trigger="hover"
                  popper-class="expertise-popover"
                >
                  <template #default>
                    <div
                      v-if="row.expertiseList && row.expertiseList.length > 0"
                      style="display: flex; flex-wrap: wrap; gap: 5px"
                    >
                      <el-tag v-for="(item, index) in row.expertiseList" :key="index" size="small">
                        {{ item.expertiseName }}
                      </el-tag>
                    </div>
                    <span v-else>暂无擅长领域</span>
                  </template>
                  <template #reference>
                    <div style="display: flex; flex-wrap: wrap; gap: 4px; justify-content: center">
                      <template v-if="row.expertiseList && row.expertiseList.length > 0">
                        <el-tag
                          v-for="(item, index) in row.expertiseList.slice(0, 4)"
                          :key="index"
                          size="small"
                        >
                          {{ item.expertiseName }}
                        </el-tag>
                        <el-tag v-if="row.expertiseList.length > 2" type="info" size="small">
                          +{{ row.expertiseList.length - 2 }}
                        </el-tag>
                      </template>
                      <span v-else>--</span>
                    </div>
                  </template>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
              label="手机号码"
              align="center"
              prop="mobile"
              width="130"
              :formatter="(row) => row.mobile || '--'"
            />
            <el-table-column label="状态" align="center" prop="status" width="70">
              <template #default="scope">
                <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
                  {{ scope.row.status == 1 ? "正常" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="140" />
            <el-table-column label="操作" fixed="right" width="250" align="center">
              <template #default="scope">
                <el-button
                  type="primary"
                  icon="RefreshLeft"
                  size="small"
                  link
                  @click="
                    (e) => {
                      e.stopPropagation();
                      hancleResetPassword(scope.row);
                    }
                  "
                >
                  重置密码
                </el-button>
                <el-button
                  type="primary"
                  icon="edit"
                  link
                  size="small"
                  @click="
                    (e) => {
                      e.stopPropagation();
                      handleOpenDialog(scope.row.id);
                    }
                  "
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  icon="delete"
                  link
                  size="small"
                  @click="
                    (e) => {
                      e.stopPropagation();
                      handleDelete(scope.row.id);
                    }
                  "
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户表单 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      size="40%"
      :close-on-click-modal="false"
      @close="handleCloseDialog"
    >
      <el-form
        ref="userFormRef"
        :disabled="isCheck"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="" prop="avatar">
          <ImageUpload v-model="formData.avatar" :limit="1" :disabled="isCheck" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            :disabled="!!formData.id"
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input
            v-model="formData.idCard"
            :disabled="!!formData.id"
            placeholder="请输入身份证号"
          />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
            placeholder="请选择所属部门"
            :data="deptOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <Dict v-model="formData.gender" code="gender" />
        </el-form-item>
        <el-form-item label="毕业院校" prop="schoolId">
          <el-select
            v-model="formData.schoolId"
            filterable
            remote
            placeholder="请输入院校名称搜索"
            :remote-method="getSchoolList"
            :loading="schoolLoading"
            @change="handleSchoolChange"
          >
            <el-option
              v-for="item in schoolOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学历" prop="academicDegreeCode">
          <Dict v-model="formData.academicDegreeCode" code="academic_degree" />
        </el-form-item>
        <el-form-item label="擅长领域" prop="expertiseList">
          <Dict v-model="formData.expertiseList" type="select-multiple" code="expertise_field" />
        </el-form-item>

        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item>

        <!-- <el-form-item label="状态" prop="status">
          <el-switch
            v-model="formData.status"
            inline-prompt
            active-text="正常"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item> -->
        <el-form-item label="身份证正面照片" prop="idCardFrontUrl">
          <ImageUpload v-model="formData.idCardFrontUrl" :limit="1" :disabled="isCheck" />
        </el-form-item>
        <el-form-item label="身份证背面照片" prop="idCardBackUrl">
          <ImageUpload v-model="formData.idCardBackUrl" :limit="1" :disabled="isCheck" />
        </el-form-item>
        <el-form-item label="学位证书照片" prop="degreeUrl">
          <ImageUpload v-model="formData.degreeUrl" :limit="1" :disabled="isCheck" />
        </el-form-item>
        <el-form-item label="其他资料" prop="otherUrl">
          <FileUpload v-model="formData.otherUrl" />
        </el-form-item>
      </el-form>

      <template v-if="!isCheck" #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 用户导入 -->
  </div>
</template>

<script setup lang="ts">
import UserAPI, { ExpertiseListType, UserForm, UserPageQuery, UserPageVO } from "@/api/system/user";

import DeptAPI from "@/api/system/dept";
import RoleAPI from "@/api/system/role";
import { getAllSchools, SchoolOption } from "@/api/school/index";
import { tr } from "element-plus/es/locale";
import { FormRules } from "element-plus";
import { EMAIL_PATTERN, MOBILE_PATTERN } from "@/constants/rules";
import { Row } from "element-plus/es/components/table-v2/src/components";
import { useDictStore } from "@/store";

defineOptions({
  name: "Counselor",
  inheritAttrs: false,
});
const dictStore = useDictStore();

const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);

const queryParams = reactive<UserPageQuery>({
  pageNum: 1,
  pageSize: 10,
  roleIds: ["13"],
});
const expertiseList = reactive<Record<string, { dictCode: string; name: string }>>({});
const academicDegreeList = reactive<Record<string, string>>({});
const pageData = ref<UserPageVO[]>();
const total = ref(0);
const loading = ref(false);
const isCheck = ref(false);
const dialog = reactive({
  visible: false,
  title: "新增咨询师",
});

const formData = reactive<UserForm>({
  status: 1,
});

const rules = reactive<FormRules>({
  username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  idCard: [
    { required: true, message: "身份证号不能为空", trigger: "blur" },
    {
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|10|11|12)(0[1-9]|[1-2][0-9]|30|31)\d{3}[0-9Xx]$/,
      message: "请输入正确的身份证号",
      trigger: "change",
    },
  ],
  deptId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  academicDegreeCode: [{ required: true, message: "请选择学历", trigger: "change" }],
  expertiseList: [{ required: true, message: "请选择擅长领域", trigger: "change" }],
  schoolId: [{ required: true, message: "请选择毕业院校", trigger: "change" }],

  email: [
    {
      required: true,
      message: "邮箱不能为空",
      trigger: "blur",
    },
    {
      pattern: EMAIL_PATTERN,
      message: "请输入正确的邮箱地址",
      trigger: "change",
    },
  ],
  mobile: [
    {
      required: true,
      message: "手机号码不能为空",
      trigger: "blur",
    },
    {
      pattern: MOBILE_PATTERN,
      message: "请输入正确的手机号码",
      trigger: "change",
    },
  ],
  idCardFrontUrl: [{ required: true, message: "身份证正面照片不能为空", trigger: "change" }],
  idCardBackUrl: [{ required: true, message: "身份证背面照片不能为空", trigger: "change" }],
  degreeUrl: [{ required: true, message: "学位证书照片不能为空", trigger: "change" }],
  otherUrl: [{ required: true, message: "其他资料不能为空", trigger: "change" }],
});

// 选中的用户ID
const selectIds = ref<number[]>([]);
// 部门下拉数据源
const deptOptions = ref<OptionType[]>();
// 角色下拉数据源
const roleOptions = ref<OptionType[]>();
// 学校下拉数据源
const schoolOptions = ref<SchoolOption[]>([]);
const schoolLoading = ref(false);
// 导入弹窗显示状态
const importDialogVisible = ref(false);

// 查询
function handleQuery() {
  loading.value = true;

  // 创建一个新的查询对象，只包含必要的分页信息和角色ID
  const cleanParams: any = {
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
    roleIds: queryParams.roleIds,
  };

  // 只添加有值的查询参数
  if (queryParams.keywords) cleanParams.keywords = queryParams.keywords;
  if (queryParams.schoolId) cleanParams.schoolId = queryParams.schoolId;
  if (queryParams.academicDegreeCodes && queryParams.academicDegreeCodes.length > 0) {
    cleanParams.academicDegreeCodes = queryParams.academicDegreeCodes;
  }
  if (queryParams.expertiseList && queryParams.expertiseList.length > 0) {
    cleanParams.expertiseList = queryParams.expertiseList;
  }
  if (queryParams.status !== undefined) cleanParams.status = queryParams.status;
  if (queryParams.createTime) cleanParams.createTime = queryParams.createTime;
  if (queryParams.deptId) cleanParams.deptId = queryParams.deptId;

  UserAPI.getPage(cleanParams)
    .then((data) => {
      // 确保每个咨询师的schoolName正确显示
      if (data.list && data.list.length > 0) {
        data.list.forEach((item) => {
          if (item.schoolId && !item.schoolName) {
            item.schoolName = `待加载(${item.schoolId})`;
          }
        });
      }
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.deptId = undefined;
  queryParams.createTime = undefined;
  queryParams.schoolId = undefined;
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}
const handleRowClick = async (row: UserPageVO) => {
  await handleOpenDialog(row.id);
  dialog.title = "咨询师详情";
  isCheck.value = true;
};
// 重置密码
function hancleResetPassword(row: UserPageVO) {
  ElMessageBox.prompt("请输入用户【" + row.username + "】的新密码", "重置密码", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(
    ({ value }) => {
      if (!value || value.length < 6) {
        ElMessage.warning("密码至少需要6位字符，请重新输入");
        return false;
      }
      UserAPI.resetPassword(row.id, value).then(() => {
        ElMessage.success("密码重置成功，新密码是：" + value);
      });
    },
    () => {
      ElMessage.info("已取消重置密码");
    }
  );
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(id?: number) {
  dialog.visible = true;
  // 加载角色下拉数据源
  roleOptions.value = await RoleAPI.getOptions();
  // 加载部门下拉数据源
  deptOptions.value = await DeptAPI.getOptions();

  if (id) {
    dialog.title = "修改咨询师";
    UserAPI.getFormData(id).then((data) => {
      Object.assign(formData, { ...data });
      formData.schoolId = data.schoolId?.toString();
      formData.otherUrl =
        data?.otherUrl?.map?.((item) => ({
          ...item,
          name: item.fileName,
          url: item.url,
        })) || [];
    });
  } else {
    dialog.title = "新增咨询师";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  // userFormRef.value.clearValidate();

  formData.id = undefined;
  isCheck.value = false;
  formData.status = 0;
  schoolOptions.value = [];
}

// 获取学校列表
async function getSchoolList(query: string) {
  schoolLoading.value = true;
  try {
    schoolOptions.value = await getAllSchools(query);
  } finally {
    schoolLoading.value = false;
  }
}

// 学校选择变化时设置学校名称
function handleSchoolChange(schoolId: number) {
  const school = schoolOptions.value.find((item) => item.id === schoolId);
  if (school) {
    formData.schoolName = school.name;
  }
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      formData.expertiseCodes = formData.expertiseList?.map((item) => {
        return expertiseList[item as string];
      });
      formData.academicDegreeName = academicDegreeList[formData.academicDegreeCode as string];

      // 确保schoolName被正确设置
      if (formData.schoolId && !formData.schoolName) {
        const schoolId =
          typeof formData.schoolId === "string" ? parseInt(formData.schoolId) : formData.schoolId;
        const school = schoolOptions.value.find((item) => item.id === schoolId);
        if (school) {
          formData.schoolName = school.name;
        }
      }

      loading.value = true;
      formData.otherUrl = formData.otherUrl?.map((item) => ({
        name: item.fileName,
        url: item.url,
        fileName: item.name,
      }));
      formData.status = 1;
      if (userId) {
        UserAPI.update(userId, formData)
          .then(() => {
            ElMessage.success("修改用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        formData.roleIds = [13];
        formData.isConsultant = true;
        UserAPI.add(formData)
          .then(() => {
            ElMessage.success("新增用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**
 * 删除用户
 *
 * @param id  用户ID
 */
function handleDelete(id?: number) {
  const userIds = [id || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      UserAPI.deleteByIds(userIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开导入弹窗
function handleOpenImportDialog() {
  importDialogVisible.value = true;
}

// 导出用户
function handleExport() {
  UserAPI.export(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(response.headers["content-disposition"].split(";")[1].split("=")[1]);
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

onMounted(() => {
  // 处理擅长领域集合
  dictStore.getDictionary("expertise_field").reduce((pre, cur) => {
    pre[cur.value] = { dictCode: cur.value, name: cur.label };
    return pre;
  }, expertiseList);
  // 处理学历集合
  dictStore.getDictionary("academic_degree").reduce((pre, cur) => {
    pre[cur.value] = cur.label;
    return pre;
  }, academicDegreeList);

  // 初始加载一些常见学校数据，以便在表格中显示
  getSchoolList("");

  handleQuery();
});
// 每次进入页面时重新查询数据
onActivated(() => {
  handleQuery();
});
</script>
